package br.net.woodstock.tickettoride.client.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import br.net.woodstock.tickettoride.client.TicketData;
import br.net.woodstock.tickettoride.client.TicketHash;
import br.net.woodstock.tickettoride.client.TicketSession;
import br.net.woodstock.tickettoride.client.beans.DefaultTicketHash;

public abstract class AbstractTicketToRideFilter implements Filter {

	public static final String	TICKET_HASH_PARAMETER		= "tickettoride.hash";

	public static final String	TARGET_PROPERTY_NAME		= "target";

	public static final String	TARGET_REQUEST_ATTRIBUTE	= TargetType.REQUEST_ATTRIBUTE.getName();

	public static final String	TARGET_REQUEST_PARAMETER	= TargetType.REQUEST_PARAMETER.getName();

	public static final String	TARGET_SESSION_ATTRIBUTE	= TargetType.SESSION_ATTRIBUTE.getName();

	private String				target;

	private TargetHandler		handler;

	@Override
	public void init(final FilterConfig config) throws ServletException {
		this.target = config.getInitParameter(AbstractTicketToRideFilter.TARGET_PROPERTY_NAME);
		this.handler = TargetType.fromName(this.target).getHandler();

	}

	@Override
	public void destroy() {
		//
	}

	@Override
	public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;

		String hash = request.getParameter(AbstractTicketToRideFilter.TICKET_HASH_PARAMETER);
		if (hash != null) {
			TicketSession session = this.getSession();
			TicketHash ticketHash = new DefaultTicketHash(hash);
			TicketData ticketData = session.getData(ticketHash);
			httpServletRequest = this.handler.handle(httpServletRequest, ticketData.getBytes());
		}

		chain.doFilter(httpServletRequest, response);
	}

	protected abstract TicketSession getSession();
}
